package com.uidp.ui;

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

import org.apache.commons.lang.StringUtils;

import com.acsior.sbc.exception.BusinessException;
import com.acsior.sbc.exception.SearchException;
import com.acsior.wu.bean.MBGeneralEditableObject;
import com.acsior.wu.messanger.Messenger;
import com.acsior.wu.nom.UIListManager;
import com.acsior.wu.utils.UIUtils;
import com.uidp.bundle.Messages;
import com.uidp.domain.Usergroups;
import com.uidp.domain.Users;
import com.uidp.security.Digester;
import com.uidp.uitils.ManagedBeans;
import com.uidp.uitils.NavOutcomes;

/**
 * Клас, който обслужва екрана за промяна на парола
 * 
 */
public class MBRegUser extends MBGeneralEditableObject<Users> {

	private List<Usergroups> allGropus = new ArrayList<Usergroups>();

	private List<String> selected = new ArrayList<String>();

	private String selectedGroup;

	/**
	 * Потвърждаване на нова парола
	 */
	private String confirmNewPassword;

	/**
	 * Текуща парола
	 */
	private String currentPassword;

	/**
	 * Нова парола
	 */
	private String newPassword;

	/**
	 * Конструктор
	 */
	@SuppressWarnings("static-access")
	public MBRegUser() {
		super(Users.class);
		try {
			this.allGropus = new Usergroups().searchActiveByUserName("");
			// getSelected().add("Избор на група");
			// if (isEditMode()) {
			// за да са избрани в режим на редакция
			// for (Usergroups r : getGeneral().getSelRoles()) {
			// this.selected.add(r.getSystemName());
			// }
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SearchException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * запис на потребител
	 */
	@SuppressWarnings("static-access")
	public String saveUsers() {
		if (isValid()) {
			try {
				getGeneral().setUsergroups(
						new Usergroups().searchActiveByUserName(
								getSelectedGroup()).get(0));
				getGeneral().setPassword(ENCRYPT_PASSWORD(getPassword()));
				
					getGeneral().store();
				
				return navigate(NavOutcomes.home);
			} catch (BusinessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SearchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * Смяна на парола
	 * 
	 * @return нав. изход
	 */
	public String changePassword() {
		if (isValid()) {

			if (!getGeneral().isPasswordSame(this.currentPassword)) {
				// Messenger.addErrorMessage(NAPWMKeys.inconstistent_old_passwod);
				return "";
			}

			try {
				getGeneral().changePassword(this.newPassword);
				// Messenger.addInfoMessage(NAPWMKeys.pwd_change_success);
				return navigate(NavOutcomes.login);
			} catch (BusinessException e) {
				Messenger.addException(e);
			}
		}
		return "";
	}

	/**
	 * @return confirmNewPassword
	 */
	public String getConfirmNewPassword() {
		return this.confirmNewPassword;
	}

	/**
	 * @return currentPassword
	 */
	public String getCurrentPassword() {
		return this.currentPassword;
	}

	/**
	 * @return newPassword
	 */
	public String getNewPassword() {
		return this.newPassword;
	}

	/**
	 * @see com.acsior.wu.bean.MBGeneralEditableObject#initData()
	 */
	@Override
	public void initData() {
		this.newPassword = "";
		this.confirmNewPassword = "";
		this.currentPassword = "";
	}

	/**
	 * @param confirmNewPassword
	 */
	public void setConfirmNewPassword(String confirmNewPassword) {
		this.confirmNewPassword = confirmNewPassword;
	}

	/**
	 * @param currentPassword
	 */
	public void setCurrentPassword(String currentPassword) {
		this.currentPassword = currentPassword;
	}

	/**
	 * @param newPassword
	 */
	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}


	/**
	 * @see MBGeneral#getManagedProp()
	 */
	@Override
	protected ManagedBeans getManagedProp() {
		return ManagedBeans.regUser;
	}

	/**
	 * @see com.acsior.wu.bean.MBGeneralEditableObject#isValid()
	 */
	protected boolean isValidPass() {
		boolean isValid = true;
		if (UIUtils.isEmpty(this.currentPassword)) {
			isValid = false;
			// Messenger.addErrorMessage(NAPWMKeys.currentPassword_missing);
		}
		if (UIUtils.isEmpty(this.newPassword)) {
			isValid = false;
			// Messenger.addErrorMessage(NAPWMKeys.newPassword_missing);
		} else {
			if (this.newPassword.length() < 6) {
				isValid = false;
				// Messenger.addErrorMessage(NAPWMKeys.newPassword_invalid);
			}
		}

		if (UIUtils.isEmpty(this.confirmNewPassword)) {
			isValid = false;
			// Messenger.addErrorMessage(NAPWMKeys.confirmPassword_missing);
		}

		if (!this.newPassword.equals(this.confirmNewPassword)) {
			isValid = false;
			// Messenger.addErrorMessage(NAPWMKeys.inconstistent_new_passwod);
		}
		return isValid;
	}

	public String getUsername() {
		return getGeneral().getUsername();
	}

	public void setUsername(String username) {
		getGeneral().setUsername(username);
	}

	public String getPassword() {
		return getGeneral().getPassword();
	}

	public void setPassword(String password) {
		getGeneral().setPassword(password);
	}

	public String getFirstName() {
		return getGeneral().getFirstName();
	}

	public void setFirstName(String firstName) {
		getGeneral().setFirstName(firstName);
	}

	public String getSurname() {
		return getGeneral().getSurname();
	}

	public void setSurname(String surname) {
		getGeneral().setSurname(surname);
	}

	public String getEgn() {
		return getGeneral().getEgn();
	}

	public void setEgn(String egn) {
		getGeneral().setEgn(egn);
	}

	public String getFamily() {
		return getGeneral().getFamily();
	}

	public void setFamily(String family) {
		getGeneral().setFamily(family);
	}

	public String getEmail() {
		return getGeneral().getEmail();
	}

	public void setEmail(String email) {
		getGeneral().setEmail(email);
	}

	@Override
	protected boolean isValid() {
		boolean isValid = true;
		if (StringUtils.isEmpty(getUsername())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.USERNAME_MISSING);
		}
		if (StringUtils.isEmpty(getNewPassword())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.PWD_MISSING);
		}
		if (StringUtils.isEmpty(getConfirmNewPassword())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.PWD_SEC_MISSING);
		}
		if (StringUtils.isEmpty(getUsername())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.NAME_MISSING);
		}
		if (StringUtils.isEmpty(getFamily())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.FAMILY_MISSING);
		}
		if (StringUtils.isEmpty(getEgn())) {
			isValid = false;
			Messenger.addErrorMessage(Messages.EGN_MISSING);
		}
		if (!this.newPassword.equals(this.confirmNewPassword)) {
			isValid = false;
			Messenger.addErrorMessage(Messages.PASS_NOT_EQUAL);
		} else {
			setPassword(getNewPassword());
		}
		// TODO validaciq za egn i grupa
		return isValid;
	}

	public List<Usergroups> getAllGropus() {
		return allGropus;
	}

	public void setAllGropus(List<Usergroups> allGropus) {
		this.allGropus = allGropus;
	}

	public List<String> getSelected() {
		return selected;
	}

	public void setSelected(List<String> selected) {
		this.selected = selected;
	}

	/**
	 * Списък с всички роли
	 * 
	 * @return List
	 */
	public List<SelectItem> getNomGroups() {

		List<Usergroups> r = getAllGropus();
		List<String> groupNames = new ArrayList<String>();
		for (Usergroups s : getAllGropus()) {
			groupNames.add(s.getGroupname());
		}
		if (r != null && !r.isEmpty()) {
			return UIListManager.buildSelectItemsFromStrings(groupNames);
		}

		return new ArrayList<SelectItem>();
	}

	public String getSelectedGroup() {
		return selectedGroup;
	}

	public void setSelectedGroup(String selectedGroup) {
		this.selectedGroup = selectedGroup;
	}

	/**
	 * @param str
	 * @return encoded string
	 */
	public static String ENCRYPT_PASSWORD(String str) {
		return Digester.digestSHA1(str);
	}

}
